document.writeln("<script type='text/javascript' src='utils.js'></script>");

//Intervals
var run_chat = self.setInterval(function(){submit_chat("");},1000);
var turn_ended;
if(turn_ended)
	waiting = self.setInterval(function(){check_if_my_turn("");},1000);

//var
var clicked = false;
var moved = 0;
var board;
var temp_hold;
var circle;
var ani_i = 0;
var ani_move_list = "";
var ani_x2 = "";
var ani_y2 = "";
var curr_x = "";
var curr_y = "";

var boardT =	"1:1:1:0:0:0:0:0:" +
"1:1:0:0:0:0:0:0:" +
"1:0:0:0:0:0:0:0:" +
"0:0:0:0:0:0:0:0:" +
"0:0:0:0:0:0:0:0:" +
"0:0:0:0:0:0:0:2:" +
"0:0:0:0:0:0:2:2:" +
"0:0:0:0:0:2:2:2:";


addLoadEvent(iniBoard);

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		};
	}
}

function create_text(i, j, value) {
	text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
	text.setAttribute("id", "text" + i + j);
	text.setAttribute("fill", "black");
	text.setAttribute("x", 20 + i*55);
	text.setAttribute("y", 20 + j*55);
	text.setAttribute("style", "fill: #000000; stroke: #FFFFFF;  font-size: 18px;");
	text.textContent= value;

	return text;
}
function create_piece(i, j){
	var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
	shape.setAttribute("id", i +"-"+ j);
	shape.setAttribute("onmousedown","mouse_down(evt)");
	shape.setAttribute("onmouseup","mouse_up(evt)");
	shape.setAttribute("onclick","mouse_click(evt)");
	shape.setAttribute("cx", 40 + i*55);
	shape.setAttribute("cy", 40 + j*55);
	shape.setAttribute("r",  20);
	shape.setAttribute("fill", "white");
	shape.setAttribute("class", "piece");

	return shape;
}

function iniBoard() {
	board = document.createElementNS("http://www.w3.org/2000/svg", "svg");
	board.setAttribute("style", "background: red");
	board.setAttribute("height", "470");
	board.setAttribute("width", "470");
	document.getElementById("boardplace").appendChild(board);
	for (var i=0;i<8;i++)
	{
		board.appendChild(create_text(i,0,i));
		board.appendChild(create_text(0,i,i));

		for (var j=0;j<8;j++)
		{
			var shape = create_piece(i ,j);
			board.appendChild(shape);
		}
	}
	updateBoard();
}

function updateBoard() {
	var xmlhttp;
	if (window.XMLHttpRequest)	// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	else // code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			var str = xmlhttp.responseText.substring(0,5);
			if(str=="upda$") {
				var ans = xmlhttp.responseText.slice(5);
				boardT =  ans;
				var tmp = boardT.split(":");
				for(var i=0;i<8;i++) {
					for(var j=0;j<8;j++) {	
						var idToStr = (i*8)+j;
						var place = i +"-"+ j;
						if(tmp[idToStr]==0)
							document.getElementById(place).setAttribute("class","piece" );
						if(tmp[idToStr]==1)
							document.getElementById(place).setAttribute("class","firstP" );
						if(tmp[idToStr]==2)
							document.getElementById(place).setAttribute("class", "secondP");
					}
				}
			}
		}
	};
	xmlhttp.open("Post","GameManager",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("&update_board=true");	
}
function check_if_my_turn() {
	var xmlhttp;
	if (window.XMLHttpRequest)	// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	else // code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			var str = xmlhttp.responseText.substring(0,5);
			if(str=="turn$") {
				var ans = xmlhttp.responseText.slice(5);
				answer = ans.split("$");
				if(answer[0]=="end_game") {
					waiting = self.clearInterval(waiting);
					run_chat = self.clearInterval(run_chat);
					clicked = false;
					document.getElementById("moves").value = "";
					moved = 0;
					boardT =  answer[1];
					if(answer[2]!="")
						start_animation(answer[2]);
					boardT =  answer[3];
					document.getElementById("cturn").innerHTML = "GAME OVER";
					post("ShowStatistics",{game_data:answer[4],at_mid_game:"false"},"post");
					return;
				} else if(answer[0]=="true") {
					document.getElementById("cturn").innerHTML = "The other player move";
					waiting = self.clearInterval(waiting);
					boardT =  answer[1];
					document.getElementById("cturn").innerHTML = "It is your turn";
					start_animation(answer[2]);
					boardT =  answer[3];
					clicked = false;
					document.getElementById("moves").value = "";
					moved = 0;
					return;
				} else if (answer[0]=="false") {
					return;
				} else {//debug
					document.getElementById("cturn").innerHTML = answer[0];
				}
			} 
		}
	};
	xmlhttp.open("Post","GameManager",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("&my_turn=true");	
}

function player_resign() {
	var xmlhttp;
	turn_ended = true;
	clicked = false;
	document.getElementById("moves").value = "";
	moved = 0;
	document.getElementById("cturn").innerHTML = "You are being transferred to Statistics Page";
	if (window.XMLHttpRequest)	// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	else // code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			var str = xmlhttp.responseText.substring(0,5);
			if(str=="resi$") {
				run_chat = self.clearInterval(run_chat);
				var ans = xmlhttp.responseText.slice(5);
				answer = ans.split("$");
				boardT =  answer[0];
				updateBoard();
				document.getElementById("cturn").innerHTML = "GAME OVER";
				post("ShowStatistics",{game_data:answer[1],at_mid_game:"false"},"post");
				return;
			} 
		}
	};
	xmlhttp.open("Post","GameManager",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("&resign=true");	
}	

function get_statistics() {
	var xmlhttp;
	if (window.XMLHttpRequest)	// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	else // code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			var str = xmlhttp.responseText.substring(0,5);
			if(str =="stat$") {
				var ans = xmlhttp.responseText.slice(5);
				answer = ans.split("$");
				if (answer[0] =="true") {
					run_chat = self.clearInterval(run_chat);
					waiting = self.clearInterval(waiting);
					post("ShowStatistics",{game_data:answer[1],at_mid_game:"true"},"post");
					return;
				}else {
					document.getElementById("cturn").innerHTML = answer[1];
					return;
				}
			} 
		}
	};
	xmlhttp.open("Post","GameManager",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("&statistics=true");	
}

function submit_move()
{
//	 if (turn_ended) 
//		 return;
	turn_ended = true;
	var xmlhttp;
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			var str = xmlhttp.responseText.substring(0,5);
			if(str=="move$") {
				var ans = xmlhttp.responseText.slice(5);
				answer = ans.split("$");
				if (answer[0]== "turn_end") {
					boardT =  answer[1];
					document.getElementById("cturn").innerHTML = "turn ended, waiting for other player to move";
					document.getElementById(clicked).setAttribute("class", player);
					clicked = false;
					document.getElementById("moves").value = "";
					moved = 0;
					updateBoard();
					waiting = self.setInterval(function(){check_if_my_turn("");},1000);
					turn_ended= true;
					return;
				}else if (answer[0]== "not_valid") {
					//set board to given board 
					document.getElementById("cturn").innerHTML = answer[1];
					boardT =  answer[2];
					clicked = false;
					document.getElementById("moves").value = "";
					moved = 0;
					updateBoard();
					turn_ended = false;
					return;
				}else if (answer[0]== "game_ended") {
					boardT =  answer[1];
					updateBoard();
					run_chat = self.clearInterval(run_chat);
					document.getElementById("cturn").innerHTML = "GAME_OVER";
					post("ShowStatistics",{game_data:answer[1],at_mid_game:"false"},"post");
					return;
				}
			}
		}
	};
	xmlhttp.open("Post","GameManager",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("&moves=" + document.getElementById("moves").value);

	document.getElementById("moves").value = "";

}

function mouse_click(evt)

{  
	if (turn_ended )
		return;
	if (! clicked )
	{
		clicked = evt.target["id"];
		mouse_down(evt);
		return;

	} 
	else if (evt.target["id"] == clicked)
		return;   
	mouse_up(evt);
	return;
}


function mouse_down(evt)
{
	if (turn_ended) 
		return;
	if (evt.target["class"] == otherPlayer)
		return;
	if (moved ==2 && evt.target["id"] != clicked)
		return;
	if (evt.target.getAttribute("class")!= player)
		return;


	clicked = evt.target["id"];
	evt.target.setAttribute("class", "pushed");
}

function mouse_up(evt)
{

	if (turn_ended || clicked==false )
		return;
	if (evt.target["class"] == otherPlayer ||  document.getElementById(clicked).getAttribute("class") == otherPlayer)
		return;
	from = clicked;
	to = evt.target["id"];
	if (! valid_move(from, to) ) 
	{
		if (moved ==0)
		{
			document.getElementById(clicked).setAttribute("class", player);

			clicked = false;
		}else if (moved ==2)
		{
			document.getElementById(clicked).setAttribute("class", "pushed");
		}
		return;
	}
	document.getElementById("moves").value += from + "->"+ to + ";";
	clicked = to;
	start_animation(from + "->" + to);
}

function submit_chat(chat_line)
{
	first = false;
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			var str = xmlhttp.responseText.substring(0,5);
			if(str=="chat$") {
				var ans = xmlhttp.responseText.slice(5);
				document.getElementById("chat_window").value =ans;// xmlhttp.responseText;
				if (chat_line != "")
				{
					document.getElementById("chat_new_line").value="";
				}
			}
		}
	};
	xmlhttp.open("Post","GameManager",true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("&chat=" + chat_line);
}


function valid_move(from, to)
{		
	//check different cases
	if (from == false) 
		return false;
	if (turn_ended)
		return false;
	if (clicked && clicked == to)
		return false;

	if (document.getElementById(to).getAttribute("class") != "piece")
		return false;
	if (document.getElementById(from).getAttribute("class") == otherPlayer) 
		return false;

	var a = from.split("-");
	var b = to.split("-");
	var x1 = parseInt(a[0]);
	var y1 = parseInt(a[1]);
	var x2 = parseInt(b[0]);
	var y2 = parseInt(b[1]);


	// HANDLE MOVED ONE:
	if (  ( (Math.abs(x1 - x2) == 1) && (Math.abs(y1 - y2) <= 1)) 
			||( (Math.abs(y1 - y2) == 1) && (Math.abs(x1 - x2) == 0)) )
	{
		if (moved == 2)
			return false; //can't move one after moved two
		clicked = to;
		moved = 1;
		turn_ended = true;
		return true;
	}

	//HANDLE MOVED TWO:
	if ( ((Math.abs(x1 - x2) == 2) && (Math.abs(y1 - y2) == 0)) ||
			((Math.abs(x1 - x2) == 0) && (Math.abs(y1 - y2) == 2)) ||
			((Math.abs(x1 - x2) == 2) && (Math.abs(y1 - y2) == 2)) )
	{
		var p_id =  (x1+x2)/2 + "-" + (y1+y2)/2;
		if (document.getElementById(p_id).getAttribute("class") != "piece") 
		{
			clicked = to;
			moved=2;	
			return true;
		}
		return false;
	}
	//other (if exists):	
	return false;
}
function game_rules()
{
	alert(
			"this game designed for two players.\n\n"+
			"In each turn the player can move one of his pieces to an empty spot,"+
			"one up|down|diagonaly\n"+
			"or two up|down|diagonaly if there is a piece in the middle.\n"+
			"The game endes when one player pieces are all at the other player start point"
	);
}

function start_animation(move_list)
{
	if (move_list == "" || move_list == null) return;
	temp_hold = turn_ended;
	turn_ended = true;
	ani_move_list = move_list.split(";");
	id = move_list.split("->")[0];
	circle = document.getElementById(id).cloneNode();
	document.getElementById(id).setAttribute("class","piece");

	board.appendChild(circle);

	do_animation();
}


function animation_ended(){
	cls = circle.getAttribute("class");
	board.removeChild(circle);

	x = (ani_x2 - 40)/55;
	y = (ani_y2 - 40)/55;
	id = x.toString() + "-" + y.toString();
	document.getElementById(id).setAttribute("class", cls);


	ani_i = 0;
	ani_move_list = "";
	ani_x2 = "";
	ani_y2 = "";
	curr_x = "";
	curr_y = "";

	turn_ended = temp_hold;

}

function do_animation(){

	if (ani_i == ani_move_list.length || ani_move_list[ani_i].length != 8) {
		animation_ended();
		return;
	}

	curr_x = circle.getAttribute("cx");
	curr_y = circle.getAttribute("cy");
	if (ani_x2 =="" || (ani_x2 ==curr_x && ani_y2 == curr_y) ){
		var ani_end = ani_move_list[ani_i].split("->")[1];		

		ani_x2 = 40 + parseInt(ani_end.split("-")[0]) * 55;
		ani_y2 = 40 + parseInt(ani_end.split("-")[1]) * 55;
	}
	if ((ani_x2 - curr_x) !=0){
		if ((ani_x2 - curr_x) >0){
			curr_x = parseInt(curr_x) + 1;
		}else{
			curr_x = parseInt(curr_x) - 1;
		}
	}

	if ((ani_y2 - curr_y) !=0){
		if ((ani_y2 - curr_y) >0){
			curr_y = parseInt(curr_y) + 1;
		}else{
			curr_y = parseInt(curr_y) - 1;
		}
	}
	circle.setAttribute("cx", curr_x);
	circle.setAttribute("cy", curr_y);

	if (ani_x2 == curr_x && ani_y2 == curr_y){
		ani_i++;
	}
	setTimeout(do_animation, 20);

}

function post(path, params, method) {
	var form = document.createElement("form");
	form.setAttribute("method", method);
	form.setAttribute("action", path);

	for(var key in params) {
		if(params.hasOwnProperty(key)) {
			var varToAdd = document.createElement("input");
			varToAdd.setAttribute("type", "hidden");
			varToAdd.setAttribute("name", key);
			varToAdd.setAttribute("value", params[key]);

			form.appendChild(varToAdd);
		}
	}
	document.body.appendChild(form);
	form.submit();
}


